/**
 * 工具函数
 */






// 封装 localstorage 的过期时间
window.Storage.prototype.setExpire = (key, value, expire = 259200000) => {
  let obj = {
    data: value,
    time: Date.now(),
    expire: expire
  };
  localStorage.setItem(key, JSON.stringify(obj));
}

window.Storage.prototype.getExpire = key => {
  let val = localStorage.getItem(key);
  if (!val) {
    return val;
  }
  val = JSON.parse(val);
  if (Date.now() - val.time > val.expire) {
    localStorage.removeItem(key);
    return null;
  }
  return val.data;
}



// 发送请求的基本路径
window.BASE_URL = "http://139.9.177.51:8099"



// 判断是否是正则

window.axios = require('../../lib/axios/axios.js')

function isRegExp(value) {

  return Object.prototype.toString.call(value) === '[object RegExp]'

}



// 正则验证
window.verify = function verify(value, reg) {

  if (isRegExp(reg)) {
    return reg.test(value)
  }

  return false
}



// 判断是否都为TRUE
window.isAllTrue = function isAllTrue(obj) {

  for (const key in obj) {
    if (!obj[key]) return false
  }

  return true
}



// 判断是否是手机号码
window.$isPhone = function (val) {

  return /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/.test(val);

}

// 判断密码是否符合要求
window.$isPassword = function (val) {

  return /^[a-zA-Z]\w{5,17}$/.test(val);

}



// 创建提示模态框

let timer;
window.$createMask = function (type = "ok", msg = "操作成功", timeout = 1000, fn) {



  if (!timer) {

    let div = document.createElement('div');
    div.className = "mask-container"
    div.innerHTML =
      `<span class='iconfont ${type}'> </span>
  <p>${msg} </p>
  `
    document.body.appendChild(div)

    timer = setTimeout(function () {
      timer = false
      document.body.removeChild(div)
      fn ? fn() : ""
    }, timeout)

  }




}


// 底部点击

window.$footerClick = function () {

  // 点击我的
  const mine = document.querySelector('#mine');
  mine.addEventListener('click', function () {
    location.href = "./mine.html"
  })


  // 点击运动
  const exercise = document.querySelector('#exercise');
  exercise.addEventListener('click', function () {
    location.href = "./run.html"
  })


  // 点击首页
  const indexPage = document.querySelector('#mIndex');
  indexPage.addEventListener('click', function () {
    location.href = "./index.html"
  })

}


// 获取用户id
window.$getUserId = function(){


  return JSON.parse(localStorage.getExpire("data")).user.userId

}





// 权限
window.$authr = function () {

  if (!localStorage.getExpire('data')) {
    location.href = "./register.html"
  }

  const data = JSON.parse(localStorage.getExpire('data'));
  if (!data.token) {
    location.href = "./register.html"
  }

}